package server.logs;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.LinkedList;

public class Log {

	private static Log global;
	private Connection connection = null;
	
	private Log(String path)
	{
		try
		{
			Class.forName("org.sqlite.JDBC");
			connection = DriverManager.getConnection("jdbc:sqlite:"+path);
			deployDatabase();
			System.out.println("Connection with database successfully estabilished");
		}
		catch(Exception e)
		{
			System.err.println("Failed to initialize database: "+e);
			e.printStackTrace();
		}
	}
	
	public synchronized static Log getGlobal()
	{
		if (global == null)
			global = new Log("global.db");
		return global;
	}
	
	private void deployDatabase() throws Exception
	{
		Statement s = connection.createStatement();
		s.execute("CREATE TABLE IF NOT EXISTS logins( login_id INTEGER PRIMARY KEY, logged_on datetime not null, login varchar(20) not null, os varchar (15) not null, osver varchar(10) not null, hostname varchar(15) not null, hostaddress varchar(17) not null, macaddress varchar(18) not null);");
	}
	
	public void login(String logName, String os, String osVer, String hostName, String hostAddress, String mac) throws Exception
	{
		connection.createStatement().executeUpdate("INSERT INTO logins VALUES(NULL, DATETIME('NOW'), '"+logName+"', '"+os+"', '"+osVer+"', '"+hostName+"', '"+hostAddress+"', '"+mac+"');");
	}
	
	public LinkedList<String[]> getAllLogins() throws Exception
	{
		LinkedList<String[]> ret = new LinkedList<String[]>();
		ResultSet rs = connection.createStatement().executeQuery("Select * from logins;");
		String[] strs;
		while (rs.next())
		{
			strs = new String[9];
			strs[0] = rs.getString("login_id");
			strs[1] = rs.getString("logged_on");
			strs[2] = rs.getString("login");
			strs[4] = rs.getString("os");
			strs[5] = rs.getString("osver");
			strs[6] = rs.getString("hostname");
			strs[7] = rs.getString("hostaddress");
			strs[8] = rs.getString("macaddress");
			ret.add(strs);
		}
		return ret;
	}
	
	public LinkedList<String[]> getLogins(int num) throws Exception
	{
		LinkedList<String[]> ret = new LinkedList<String[]>();
		ResultSet rs = connection.createStatement().executeQuery("Select * from logins order by logged_on desc limit 0,"+num+";");
		String[] strs;
		while (rs.next())
		{
			strs = new String[8];
			strs[0] = rs.getString("login_id");
			strs[1] = rs.getString("logged_on");
			strs[2] = rs.getString("login");
			strs[4] = rs.getString("os");
			strs[5] = rs.getString("osver");
			strs[6] = rs.getString("hostname");
			strs[7] = rs.getString("hostaddress");
			ret.add(strs);
		}
		return ret;
	}
}
